<?
function drizzo_get_post_id($post_permalink) {
	drizzo_db_connect();
	global $drizzo_posts;
	$post_id_lookup = @mysql_query("SELECT `ID` FROM `$drizzo_posts` WHERE `permalink_name`='$post_permalink'");
	if($post_id_lookup) {
		$post_id = mysql_fetch_array($post_id_lookup);
		$post_id = $post_id['ID'];
	} else {
		$post_id = false;
	}
	return $post_id;
}

function drizzo_get_the_post($query_id = 0) {
	drizzo_db_connect();

	global $drizzo_posts, $drizzo_post_id, $drizzo_comments;
	
	$the_post = mysql_query("SELECT * FROM `$drizzo_posts` WHERE `ID`='$query_id' LIMIT 1");
	if(!$the_post) {
		echo "<p>Post could not be found.</p>";
		return false;
	} else {
		while($row = mysql_fetch_array($the_post)) {
			$author_query = mysql_query("SELECT `nice_name`,`username` FROM `$drizzo_users` WHERE `ID`='$row[author]'");
			if($author_query) {
				while($author_row = mysql_fetch_array($author_query)) {
					$author = $author_row['nice_name'];
					if($author == "") {
						$author = $author_row['username'];
					}
				}				
			}
			$comments_query = mysql_query("SELECT * FROM `$drizzo_comments` WHERE `post_id`='$query_id' AND `status` LIKE '%approved%'");
			
			if($comments_query) {
				$comments = mysql_num_rows($comments_query);				
			} else {
				$comments = 0;
			}

			$the_post = array(
				"ID" => $query_id,
				"author" => $row['author'],
				"author_nicename" => $author,
				"type" => $row['type'],
				"status" => $row['status'],
				"page_parent" => $row['page_parent'],
				"page_order" => $row['page_order'],
				"title" => stripslashes($row['title']),
				"content" => stripslashes($row['content']),
				"tags" => $row['tags'],
				"comment_status" => $row['comment_status'],
				"comment_count" => $comments,
				"posted_date" => (date("M d, Y", $row['posted_date']) . " at " . date("g:i A", $row['posted_date'])),
				"posted_date_raw" => $row['posted_date'],
				"edited_date" => (date("M d, Y", $row['edited_date']) . " at " . date("g:i A", $row['edited_date'])),
				"edited_date_raw" => $row['edited_date'],
				"edited_by" => $row['edited_by'],
				"menu_name" => $row['menu_name'],
				"permalink_name" => $row['permalink_name'],
				"lat" => $row['lat'],
				"lon" => $row['lon'],
				"old_id" => $row['old_id']
			);

			return $the_post;

		}
	}
}

function drizzo_get_the_posts($limit = null, $offset = null, $status = "publish,private", $types = "blog,aside") {
	global $drizzo_posts, $drizzo_comments, $drizzo_users;

	if(!$limit) {
		$limit = $_GET['limit'];
	}
	if($offset == null && $_GET['offset']) {
		$offset = $_GET['offset'];
	} elseif($offset == null) {
		$offset = 0;
	} else {
	}
	
	$statuses = explode(",", $status);
	for($i =0; $i < count($statuses); $i++) {
		if($i < (count($statuses) -1)) {
			$status_string .= "'" . $statuses[$i] . "', ";
		} else {
			$status_string .= "'" . $statuses[$i] . "'";
		}
	}
	
	$status = $status_string;

	$type_list = explode(",", $types);
	for($i =0; $i < count($type_list); $i++) {
		if($i < (count($type_list) -1)) {
			$type_string .= "'" . $type_list[$i] . "', ";
		} else {
			$type_string .= "'" . $type_list[$i] . "'";
		}
	}
	
	$types = $type_string;
	
	drizzo_db_connect();

	if($limit == 0) {
		$the_posts_query = mysql_query("SELECT * FROM `$drizzo_posts` WHERE `status` IN ($status) AND `type` IN ($types) ORDER BY `ID` DESC");
	} else {
		$the_posts_query = mysql_query("SELECT * FROM `$drizzo_posts` WHERE `status` IN ($status) AND `type` IN ($types) ORDER BY `ID` DESC LIMIT $offset,$limit");
	}

	if(!$the_posts_query) {
		echo "<p>Posts could not be retrieved.</p>";
	} else {
		while($row = mysql_fetch_array($the_posts_query)) {
			$author_query = mysql_query("SELECT `nice_name`,`username` FROM `$drizzo_users` WHERE `ID`='$row[author]'");
			if($author_query) {
				while($author_row = mysql_fetch_array($author_query)) {
					$author = $author_row['nice_name'];
					if($author == "") {
						$author = $author_row['username'];
					}
				}				
			}

			$comments_query = mysql_query("SELECT * FROM `$drizzo_comments` WHERE `post_id`='$row[ID]' AND `status`='approved'");
			if($comments_query) {
				$comments = mysql_num_rows($comments_query);				
			} else {
				$comments = 0;
			}

			$the_posts[] = array(
				"ID" => $row['ID'],
				"author" => $row['author'],
				"author_nicename" => $author,
				"type" => $row['type'],
				"status" => $row['status'],
				"page_parent" => $row['page_parent'],
				"page_order" => $row['page_order'],
				"title" => stripslashes($row['title']),
				"content" => stripslashes($row['content']),
				"tags" => $row['tags'],
				"comment_status" => $row['comment_status'],
				"comment_count" => $comments,
				"posted_date" => (date("M d, Y", $row['posted_date']) . " at " . date("g:i A", $row['posted_date'])),
				"posted_date_raw" => $row['posted_date'],
				"edited_date" => (date("M d, Y", $row['edited_date']) . " at " . date("g:i A", $row['edited_date'])),
				"edited_date_raw" => $row['edited_date'],
				"edited_by" => $row['edited_by'],
				"menu_name" => $row['menu_name'],
				"permalink_name" => $row['permalink_name'],
				"lat" => $row['lat'],
				"lon" => $row['lon']
				);
				
		}
	}
	return $the_posts;
}

function drizzo_get_the_asides($limit = 1) {
	$the_posts = drizzo_get_the_posts($limit, 0, "publish", "aside");
	return $the_posts;
}

function drizzo_asides($limit = 1) {
	$the_posts = drizzo_get_the_asides($limit);
	$asides_string .= "<ul id=\"asides\">\n";
	if(count($the_posts) > 0) {
		foreach($the_posts as $the_post) {
			$asides_string .= "\t<li class=\"aside\"><strong>" . $the_post['title'] . "</strong><br />" . $the_post['content'] . "</li>\n";
		}

	} else {
		$asides_string .= "<li>There are no asides.</li>\n";
	}
	$asides_string .= "</ul>\n";
	return $asides_string;
}

function drizzo_post_id() {
	global $the_post;

	$id= "";
	
	if(!$the_post) {
		return false;
	} else {
		$id = $the_post['ID'];
		return $id;
	}
}

function drizzo_post_title() {
	global $the_post;
	
	$title= "";
	
	if(!$the_post) {
		return false;
	} else {
		$title = $the_post['title'];
		return $title;
	}
}

function drizzo_page_menu_name($id = null) {
	if($id) {
		$this_post = drizzo_get_the_post($id);
		return $this_post['menu_name'];
	} else {
		return false;
	}
}

function drizzo_post_author($var = "ID", $id = null) {
	global $the_post, $drizzo_users;
	
	$author = "";
	
	if(!$the_post && $id == null) {
		return false;
	} else {
		if($id > 0) {
			$the_post = drizzo_get_the_post($id);
		}
		if($var == "ID") {
			$author = $the_post['author'];
		}

		if(($var == "nice_name") || ($var == "nickname") || ($var == "nicename")) {
			$author_id = $the_post['author'];
			$author_lookup = mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$author_id'");
			if($author_lookup) {
				while($row = mysql_fetch_array($author_lookup)) {
					$author = $row['nice_name'];
				}
			}
		}

		if(($var == "firstname") || ($var == "first_name") || ($var == "first")) {
			$author_id = $the_post['author'];
			$author_lookup = mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$author_id'");
			if($author_lookup) {
				while($row = mysql_fetch_array($author_lookup)) {
					$author = $row['first_name'];
				}
			}
		}

		if(($var == "lastname") || ($var == "last_name") || ($var == "last")) {
			$author_id = $the_post['author'];
			$author_lookup = mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$author_id'");
			if($author_lookup) {
				while($row = mysql_fetch_array($author_lookup)) {
					$author = $row['last_name'];
				}
			}
		}
		
		if(($var == "fullname") || ($var == "full_name")) {
			$author_id = $the_post['author'];
			$author_lookup = mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$author_id'");
			if($author_lookup) {
				while($row = mysql_fetch_array($author_lookup)) {
					$author = $row['first_name'] . " " . $row['last_name'];
				}
			}
		}

		return $author;
	}
}

function drizzo_post_status() {
	global $the_post;
	
	$status = "";
	
	if(!$the_post) {
		return false;
	} else {
		$status = $the_post['status'];
		return $status;
	}
}

function drizzo_post_order() {
	global $the_post;
	
	$order = "";
	
	if((!$the_post) || ($the_post['type'] != "page")) {
		return false;
	} else {
		$order = $the_post['page_order'];
		return $order;
	}
}

function drizzo_post_content($length = null, $word_count = 150) {
	global $the_post;
	
	$content = "";
	$excerpt = "";
	
	if(!$the_post) {
		return false;
	} else {
		$content = $the_post['content'];
		
		if(!$length || ($length == "excerpt" && str_word_count($content) <= $word_count)) {
			return drizzo_texturize($content);
		}
		
		if($length == "excerpt" && str_word_count($content) > $word_count) {
			$excerpt = strip_tags($content,'<br />,<pre>,<code>,<blockquote>,<p>');
			$excerpt = explode(" ", $excerpt);
			for($i = 0; $i < $word_count; $i++) {
				$content_string .= $excerpt[$i] . " ";
			}
			$content_string .= "<p><a href=\"" . drizzo_post_permalink() . "\">Read on...</a></p>";
			return $content_string;
		}
	}
}

function drizzo_post_content_backend() {
	global $the_post;
	return $the_post['content'];
}

function drizzo_post_excerpt($word_count = 150) {
	$excerpt = drizzo_post_content("excerpt", $word_count);
	return $excerpt;
}

function drizzo_post_date($var = "all") {
	global $the_post;
	
	$date = "";
	
	if(!$the_post) {
		$date = false;
	} else {
		if($var == "all") {
			$date = $the_post['posted_date'];
		} elseif($var == "year") {
			$date = $the_post['posted_date_raw'];
			$date = date("Y", $date);
		} elseif($var == "month") {
			$date = $the_post['posted_date_raw'];
			$date = date("m", $date);
		} elseif($var == "date") {
			$date = $the_post['posted_date_raw'];
			$date = date("d", $date);
		} elseif($var == "day") {
			$date = $the_post['posted_date_raw'];
			$date = date("l", $date);
		} elseif($var == "hour") {
			$date = $the_post['posted_date_raw'];
			$date = date("h", $date);
		} elseif($var == "hour_24") {
			$date = $the_post['posted_date_raw'];
			$date = date("H", $date);
		} elseif(($var == "minutes") || ($var == "minute")) {
			$date = $the_post['posted_date_raw'];
			$date = date("m", $date);
		} elseif($var == "seconds") {
			$date = $the_post['posted_date_raw'];
			$date = date("s", $date);
		} elseif($var == "raw") {
			$date = $the_post['posted_date_raw'];
		} else {
			$date = $the_post['posted_date_raw'];
			$date = date($var, $date);
		}
	}
	return $date;
}

function drizzo_post_edit_date($var = "all") {
	global $the_post;
	
	$edit_date = "";
	
	if(!$the_post) {
		$date = false;
	} else {
		if($var == "all") {
				$date = $the_post['edited_date'];
			} elseif($var == "year") {
				$date = $the_post['edited_date_raw'];
				$date = date("Y", $date);
			} elseif($var == "month") {
				$date = $the_post['edited_date_raw'];
				$date = date("m", $date);
			} elseif($var == "date") {
				$date = $the_post['edited_date_raw'];
				$date = date("d", $date);
			} elseif($var == "day") {
				$date = $the_post['edited_date_raw'];
				$date = date("l", $date);
			} elseif($var == "hour") {
				$date = $the_post['edited_date_raw'];
				$date = date("h", $date);
			} elseif($var == "hour_24") {
				$date = $the_post['edited_date_raw'];
				$date = date("H", $date);
			} elseif(($var == "minutes") || ($var == "minute")) {
				$date = $the_post['edited_date_raw'];
				$date = date("m", $date);
			} elseif($var == "seconds") {
				$date = $the_post['edited_date_raw'];
				$date = date("s", $date);
			} elseif($var == "raw") {
				$date = $the_post['edited_date_raw'];
			} else {
				$date = $the_post['edited_date_raw'];
			$date = date($var, $date);
		}
	}
	return $date;
}

function drizzo_post_editor($var = "ID") {
	global $the_post, $drizzo_users;
	
	$editor = "";
	
	if(!$the_post) {
		return false;
	} else {

		if($var == "ID") {
			$editor = $the_post['edited_by'];
		}

		if(($var == "nice_name") || ($var == "nickname") || ($var == "nicename")) {
			$editor_id = $the_post['edited_by'];
			$editor_lookup = mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$editor_id'");
			if($editor_lookup) {
				while($row = mysql_fetch_array($editor_lookup)) {
					$editor = $row['nice_name'];
				}
			}
		}

		if(($var == "firstname") || ($var == "first_name") || ($var == "first")) {
			$editor_id = $the_post['editor'];
			$editor_lookup = mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$editor_id'");
			if($editor_lookup) {
				while($row = mysql_fetch_array($editor_lookup)) {
					$editor = $row['first_name'];
				}
			}
		}

		if(($var == "lastname") || ($var == "last_name") || ($var == "last")) {
			$editor_id = $the_post['editor'];
			$editor_lookup = mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$editor_id'");
			if($editor_lookup) {
				while($row = mysql_fetch_array($editor_lookup)) {
					$editor = $row['last_name'];
				}
			}
		}
		
		if(($var == "fullname") || ($var == "full_name")) {
			$editor_id = $the_post['editor'];
			$editor_lookup = mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$editor_id'");
			if($editor_lookup) {
				while($row = mysql_fetch_array($editor_lookup)) {
					$editor = $row['first_name'] . " " . $row['last_name'];
				}
			}
		}

		return $editor;
	}
}

function drizzo_post_tags($id = null, $style = "comma", $links = "true") {
	global $drizzo_posts, $the_post;
	
	drizzo_db_connect();
	
	if($id == null && empty($the_post)) {
		return false;
	} else {
		if($id > 0) {
			$the_post = drizzo_get_the_post($id);
		}

		$tags = explode(", ", $the_post['tags']);
		$tags_lower = array_map('strtolower', $tags);
		array_multisort($tags_lower, SORT_ASC, SORT_STRING, $tags);

		if($style == "comma") {
				$tag_count = 1;
				$tags_string = null;
				foreach($tags as $tag) {
					$tag_nice = str_replace("-", " ", $tag);
					if($links == "true") {
						if($tag_count < count($tags)) {
							$tags_string .= "<a href=\"/tags/" . $tag . "\">" . $tag_nice . "</a>, ";
						} else {
							$tags_string .= "<a href=\"/tags/" . $tag . "\">" . $tag_nice . "</a>";
						}
					} else {
						if($tag_count < count($tags)) {
							$tags_string .= $tag_nice . ", ";
						} else {
							$tags_string .= $tag_nice;
						}
					}
					$tag_count++;
				}

			return $tags_string;
		}
		
		if($style == ("list" || "ul" || "ol")) {
			if($style == ("list" || "ul")) { $list_type = "ul"; }
			if($style ==("ol")) { $list_type = "ol"; }
			
			$tags_query = mysql_query("SELECT `tags` FROM `$drizzo_posts` WHERE `ID`='$id'");
			if($tags_query) {
				while($row = mysql_fetch_array($tags_query)) {
					$tags = $row['tags'];
				}
				$tag = explode(", ", $tags);
				$tag_lower = array_map('strtolower', $tag);
				array_multisort($tag_lower, SORT_ASC, SORT_STRING, $tag);
				$tag_count = count($tag);
				$tags_string .= "<" . $list_type . " id=\"tags-list\">\n";
					for($no = 0; $no < $tag_count; $no++) {
						if($links == "true") {
							$tag_nice[$no] = preg_replace("/-/", " ", $tag[$no]);
							$tags_string .= "\t<li class=\"tag\"><a href=\"/tags/" . $tag[$no] . "\">" . $tag_nice[$no] . "</a></li>\n";
						} else {
							$tag_nice[$no] = preg_replace("/-/", " ", $tag[$no]);
							$tags_string .= "\t<li class=\"tag\">" . $tag[$no] . "</li>\n";
						}
					}
				$tags_string .= "</" . $list_type . ">\n";

				return $tags_string;
			} else {
				return false;
			}
		}
	}
}

function drizzo_post_permalink($id = null) {
	global $the_post, $drizzo_options, $the_posts;
	
	if($id != null) {
		$the_post = drizzo_get_the_post($id);
	}
	
	drizzo_db_connect();
	
	if(!$the_post) {
		return false;
	} else {
		$use_permalinks_query = mysql_query("SELECT `value` FROM `$drizzo_options` WHERE `name`='use_permalinks'");
		if(!$use_permalinks_query) {
			$use_permalinks = 0;
		} else {
			$use_permalinks = mysql_fetch_array($use_permalinks_query);
			$use_permalinks = $use_permalinks[0][value];

			if($use_permalinks == 0) {
				$the_permalink = "http://" . domain_name . "/?view=" . $the_post['ID'];
			} else {
				if($the_post['type'] == 'page') {
					$the_permalink = "http://" . domain_name . "/" . drizzo_page_permalink($the_post['ID'],null);
				} else {
					$the_permalink = "http://" . domain_name . "/" . $the_post['type'] . "/" . $the_post['permalink_name'] . "/";
				}
			}
		}
		return $the_permalink;
	}
}

function drizzo_page_ancestor($id = null) {
	if($id == null) {
		global $drizzo_post_id;
		$id = $drizzo_post_id;
	}
	$ancestor = drizzo_page_parent($id);
	if(drizzo_page_parent($ancestor) > 0) {
		drizzo_page_parent($ancestor);
	} else {
		return $ancestor;
	}
}

function drizzo_page_parent($id) {
	global $drizzo_posts;
	$parent_lookup = mysql_query("SELECT `page_parent` FROM `$drizzo_posts` WHERE `ID`='$id'");
	if($parent_lookup) {
		while($row = mysql_fetch_array($parent_lookup)) {
			$parent = $row['page_parent'];
		}
	} else {
		$parent = false;
	}
	return $parent;
}

function drizzo_page_children($id) {
	global $drizzo_posts;
	$children_lookup = @mysql_query("SELECT `ID` FROM `$drizzo_posts` WHERE `page_parent`='$id' AND `type` IN ('page')");
	if($children_lookup) {
		while($row = mysql_fetch_array($children_lookup)) {
			$children[] = $row['ID'];
		}
	} else {
		$children = false;
	}
	return $children;
}

function drizzo_page_permalink($id = null, $permalink = null) {
	global $the_post, $drizzo_posts;
	if($id != null) {
		$this_post = drizzo_get_the_post($id);
	} elseif($id == null && !empty($the_post)) {
		$this_post = $the_post;
	}

	if($this_post['page_parent'] > 0) { // If the page has a parent
		if($permalink == null) { // If this function is looping through for the first time
			$permalink = $this_post['permalink_name'] . "/";
		} else { // If this function is looping
			$permalink = $this_post['permalink_name'] . "/" . $permalink;
		}		
		$permalink = drizzo_page_permalink($this_post['page_parent'],$permalink);
	} else { // If the page is top level
		if($permalink == null) { // If this function is looping through for the first time
			$permalink = $this_post['permalink_name'] . "/";
		} else { // If this function is looping
			$permalink = $this_post['permalink_name'] . "/" . $permalink;
		}
	}
	return $permalink;
}

function drizzo_related_pages($depth = 5) {
	global $drizzo_post_id;
	if($drizzo_post_id) {
		$this_post = drizzo_get_the_post($drizzo_post_id);
		if($this_post['page_parent'] == 0) {
			return drizzo_pages($drizzo_post_id, $depth);
		} else {
			return drizzo_pages(drizzo_page_ancestor($drizzo_post_id), $depth);
		}
	} else {
		return false;
	}
}

function drizzo_pages($parent = null, $depth = 0) {
	global $drizzo_posts, $the_post;
	if($parent < 0 || drizzo_pages_loop($parent, $depth) == false) {
		$pages = false;
	} else {
		$pages = drizzo_pages_loop($parent, $depth);

		$pages = "<ul class=\"pages_list\">\n" . $pages . "</ul>\n";
	}
	
	return $pages;
}

function drizzo_pages_loop($parent = null, $depth = 0, $sub_no = 0) {
		$children = drizzo_page_children($parent);
		if($children) {
			foreach($children as $child) {
				$this_post = drizzo_get_the_post($child);
				$pages .= "<li id=\"" . $this_post['permalink_name'] . "\"";
				if($child == $_GET['id'] || $child == drizzo_page_ancestor($_GET['id'])) {
					$pages .= " class=\"current sub$sub_no\"";
				} else {
					$pages .= " class=\"sub$sub_no\"";
				}
				$pages .= "><a href=\"" . drizzo_post_permalink($child) . "\" title=\"" . drizzo_post_title($child) . "\">" . drizzo_page_menu_name($child) . "</a></li>\n";
				if($sub_no < $depth) {
					if(drizzo_page_children($child)) {
						$sub_no++;
						$pages .= drizzo_pages_loop($child, $depth, $sub_no);
					}
				}
			}
		}
	return $pages;
}

function drizzo_last_post_date() {
	global $drizzo_posts;
	
	drizzo_db_connect();
	
	$now = time();
	
	$lookup = @mysql_query("SELECT `posted_date` FROM `$drizzo_posts` WHERE `posted_date`<'$now' ORDER BY `posted_date` LIMIT 1");
	if($lookup) {
		$last_date = mysql_fetch_array($lookup);
		$last_date = $last_date['posted_date'];
		return $last_date;
	} else {
		return false;
	}
}

function drizzo_texturize($text) {

// Split the text block into paragraphs
	$text = preg_replace(array('/\A\n+/', '/\n+\z/'), '', $text);
	$paragraphs = preg_split('/\n/', $text, -1, PREG_SPLIT_NO_EMPTY);

// Reinitialize the $text variable
	$text = '';

// Loop through each entry in the paragraphs array and append <p>,</p>, and <br /> where appropriate
	foreach($paragraphs as $paragraph) {
		$paragraph = trim($paragraph);
		if(preg_match("'<pre(.*)?>'i",$paragraph) || preg_match("'<code(.*)?>'i",$paragraph)) {
			$code_block_check++;
		}
		$block_level_tags = array('ul','li','blockquote','p','h1','h2','h3','h4','h5','h6','ol','pre','code');
		if($paragraph == null) {
			$block_level_tag_check = false;
			foreach($block_level_tags as $block_level_tag) {
				$block_level_tag_check = preg_match("'(</$block_level_tag(.*)?>)'i",substr($prev_paragraph, -12, 12));
			}
			if($block_level_tag_check == false && $code_block_check == 0) {
				$text .= "</p>\n";
			} else {
				$text .= "\n";
			}

		} else {
			if($prev_paragraph == '') {
				$block_level_tag_check = false;
				foreach($block_level_tags as $block_level_tag) {
					$block_level_tag_check = preg_match("'(<$block_level_tag(.*)?>)'i",substr($paragraph,0,12));
				}
				if($block_level_tag_check == false && substr($paragraph,0,4) != '<!--' && $code_block_check == 0) {
					$text .= "<p>" . $paragraph;
				} else {
					$text .= $paragraph;
				}
			} else {
				$block_level_tag_check = false;
				foreach($block_level_tags as $block_level_tag) {
					if(preg_match("'(<$block_level_tag(.*)?>)'",substr($paragraph,0,12))) {
						$block_level_tag_check = true;
					}
				}
				if(substr($prev_paragraph, -6, 6) != "<br />" && $block_level_tag_check == false && $code_block_check == 0) {
					$text .= "<br />\n" . $paragraph;
				} else {
					$text .= "\n" . $paragraph;
				}
			}
		}
		if(preg_match("'</pre(.*)?>'i",$paragraph) || preg_match("'</code(.*)?>'i",$paragraph)) {
			$code_block_check = 0;
		}
		$prev_paragraph = $paragraph;
	}
	$text .= "</p>";

// Replace "s and 's with fancy quotes
	$quote_conditions = array('/( )"/', '/"(.?)/','/( )\'/','/\'(.?)/');
	$quote_replacers = array(" &#8220;","&#8221;$1"," &#8216;","&#8217;$1");
	$text = preg_replace($quote_conditions, $quote_replacers, $text);

// Protect img, object, and embed links from the autolink capabilities
	$protected_tags = array("img","object","embed","link","script");
	foreach($protected_tags as $protected_tag) {
		preg_match_all("'(<$protected_tag(.*)>)'",$text,$protected_tag_info);
		$protected_tag_info = $protected_tag_info[0];
		foreach($protected_tag_info as $foobar) {
			$text = str_replace($foobar, str_replace(array('http://','www.'),array('h-t-t-p-:-/-/-','w-w-w-.-'),$foobar),$text);
		}
	}

// Call the autolinks function if the option is enabled
	if(drizzo_global_options('autolinks')) {
		$text = drizzo_autolinks($text);
	}

// Encode special characters as html hex equivalents.
	$plaintext = array('/“/','/”/','/&nbsp;/','/--/','/ -- /', '/---/', '/(?<!&)#/');
	$htmlchars = array("&#8220;","&#8221;","&#160;","&#8211;"," &#8211;", "&#8212;", "&#35;");
	$text = preg_replace($plaintext, $htmlchars, $text);

// Fix "s, 's, and --s inside of <tags>
	preg_match_all('/<(.*?)>/', $text, $tags);
	$tags = $tags[0];
	foreach($tags as $tag) {
		$chars_html = array('&#8221;','&#8217;','&#8211;');
		$chars_orig = array('"',"'",'--');
		$new_tags[] = str_replace($chars_html,$chars_orig, $tag);
	}
	$text = str_replace($tags, $new_tags, $text);

// Make URLs and email addresses links; Taken from http://us3.php.net/preg_replace
	$links = array('/(?(?=<a[^>]*>.+<\/a>)(?:<a[^>]*>.+<\/a>)|([^="\']?)((?:https?|ftp|bf2|):\/\/[^<> \n\r]+))/iex',
		'/<a([^>]+)>/i',
		'/(^|\s)(www.[^<> \n\r]+)/iex',
		'/(([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+)(\\.[A-Za-z0-9-]+)*)/iex');
	$new_links = array("stripslashes((strlen('\\2')>0?'\\1<a href=\"\\2\" title=\"\\2\">\\2</a>\\3':'\\0'))",
		'<a\\1>',
		"stripslashes((strlen('\\2')>0?'\\1<a href=\"http://\\2\" title=\"\\0\">\\2</a>\\3':'\\0'))",
		"stripslashes((strlen('\\2')>0?'<a href=\"mailto:\\0\" title=\"Email \\0\">\\0</a>':'\\0'))");
	$text = preg_replace($links,$new_links, $text);
	
// Restore the protected tags links
	$text = str_replace(array('h-t-t-p-:-/-/-','w-w-w-.-'),array('http://','www.'),$text);
	
// Send the text block back
  	return $text;
}

function drizzo_autolinks($text) {
	global $drizzo_links;
	$case_sensitive = drizzo_global_options('autolinks_case_sensitive');
	$all_links = drizzo_global_options('autolinks_all');
	if(!preg_match("'<!--autolink off-->'",$text)) {
		$links_lookup = @mysql_query("SELECT `name`,`url` FROM `$drizzo_links` ORDER BY `name`");
		if($links_lookup) {
			while($row = mysql_fetch_array($links_lookup)) {
				$links[] = array(
						"title" => $row['name'],
						"url" => $row['url']
					);
			}
			foreach($links as $link) {
				if($all_links) {
					if($case_sensitive) {
						$text = preg_replace("/( |\(|<p>|&#8220;|&#8216;)($link[title])( |.|\)|<\/p>|&#8221;|&#8217;)+/", "\\1<a href=\"$link[url]\" title=\"$link[title]\">\\2</a>\\3", $text);
					} else {
						$text = preg_replace("/( |\(|<p>|&#8220;|&#8216;)($link[title])( |.|\)|<\/p>|&#8221;|&#8217;)/i", "\\1<a href=\"$link[url]\" title=\"$link[title]\">\\2</a>\\3", $text);
					}
				} else {
					if($case_sensitive) {
						$first_link = substr($text,strpos($link['title'],$text),strlen($link['title']));
						$first_url = "<a href=\"$link[url]\" title=\"$link[title]\">$link[title]</a>";
						$text = preg_replace("/( |\(|<p>|&#8220;|&#8216;)($link[title])( |.|\)|<\/p>|&#8221;|&#8217;)/", "\\1<a href=\"$link[url]\" title=\"$link[title]\">\\2</a>\\3", $text);
					} else {
						$text = preg_replace("/( |\(|<p>|&#8220;|&#8216;)($link[title])( |.|\)|<\/p>|&#8221;|&#8217;)/i", "\\1<a href=\"$link[url]\" title=\"$link[title]\">\\2</a>\\3", $text);
					}
				}
			}
		}
	}

// Look for the {{}} autolink escapers and remove them
	$text = preg_replace('/\{\{([\w]+)\}\}/', "\\1", $text);

	return $text;
}

function drizzo_permalink_check($permalink_name, $id) {
	$lookup = drizzo_permalink_check_loop($permalink_name, $id);
	if($lookup == 0) {
		return $permalink_name;
	} else {
		$i = 1;
		while(drizzo_permalink_check_loop($permalink_name . "-" . $i, $id) >= 0) {
			if(drizzo_permalink_check_loop($permalink_name . "-" . $i, $id) == 0) {
				return $permalink_name . "-" . $i;
			}
			$i++;
		}
	}
}

function drizzo_permalink_check_loop($permalink_name, $id) {
	global $drizzo_posts;
	drizzo_db_connect();
	$permalink_lookup = mysql_query("SELECT `permalink_name` FROM `$drizzo_posts` WHERE `permalink_name`='$permalink_name' AND `ID`!='$id'");
	return mysql_num_rows($permalink_lookup);	
}
?>